package com.qf.cloud2203.gentoken.controller;

import cn.hutool.jwt.JWT;
import com.qf.cloud2203.domain.constants.Constants;
import com.qf.cloud2203.domain.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/vote")
public class VoteController {

    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 获取token
     *
     * @param phone
     * @return
     */
    @GetMapping("/token")
    public ResultVo gettoken(@RequestParam("phone") String phone) {
        String redisJwt = (String) redisTemplate.opsForValue().get(phone);
        if (redisJwt != null) {
            return ResultVo.ok(redisJwt);
        } else {
            String token = JWT.create()
                    .setPayload("phone", phone)
                    .setExpiresAt(new Date(System.currentTimeMillis() + 60 * 1000))
                    .setKey(Constants.SECRET.getBytes(StandardCharsets.UTF_8))
                    .sign();
            redisTemplate.opsForValue().set(Constants.SECRET + phone, token, 60, TimeUnit.SECONDS);
            return ResultVo.ok(token);
        }

    }
}










